<template>
  <el-dialog v-model="dialogVisible" title="个人信息" width="500px" draggable>
    <el-form ref="ruleFormRef" style="overflow-y: auto" :rules="rules" :model="editUser" label-width="60px">
      <el-form-item prop="workNo" label="工号">
        <el-input v-model="editUser.workNo" placeholder="请输入工号，用于突击申请"></el-input>
      </el-form-item>
      <el-form-item prop="nickName" label="简称">
        <el-input v-model="editUser.nickName" placeholder="请输入个人简称"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import apiService from "@/api/services/apiService";
import { EditUser } from "@/api/types/base";
import { BusinessOptType, BusinessType } from "@/enums/sysEnum";
import { useUserStore } from "@/stores/modules/user";
import { ElMessage, FormInstance } from "element-plus";
import { onMounted } from "vue";
import { reactive, ref } from "vue";
import { useUserAction } from "@/hooks/useUserAction";

const user = useUserStore();
const { addUserAction } = useUserAction(BusinessType.USER);

const rules = reactive({
  workNo: [{ required: true, message: "请输入工号" }]
});

const editUser = ref<EditUser>({
  _id: "",
  workNo: "",
  nickName: ""
});

onMounted(() => {
  editUser.value._id = user.userInfo._id;
  editUser.value.workNo = user.userInfo.workNo;
  editUser.value.nickName = user.userInfo.nickName;
});

const dialogVisible = ref(false);
const openDialog = () => {
  dialogVisible.value = true;
};

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      await apiService.updateById("users", editUser.value);
      if (!user.userInfo.workNo) {
        user.userInfo.workNo = editUser.value.workNo;
      }
      ElMessage.success({ message: "个人信息更新成功" });
      addUserAction(editUser.value._id, BusinessOptType.UPDATE, editUser.value.workNo);
      dialogVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};

defineExpose({ openDialog });
</script>
